import { message } from "antd"
import { createCacher } from "../cache/cacheService"

//创建缓存器
const cacher = createCacher('validateCache', (validaterName) => {
    const validatersContext = require.context('./functions', true, /\.js$/)
    for (let filePath of validatersContext.keys()) {
        if (filePath.replace('./', '').replace('.js', '') === validaterName) {
            return validatersContext(filePath).default
        }
    }
    return () => true
})

/**
 * 获取校验方法
 * @param {*} validaterName 
 */ 
function getValidater(validaterName) {
    return cacher.syncGet(validaterName)
}

/**
 * 表单校验
 * @param {*} refArray 组件ref数组
 * @returns 
 */
async function validateForm(refArray) {
    let validateResult = true
    let validateMessageArr = []
    if (refArray.length > 0) {
        for (let i = 0; i < refArray.length; i++) {
            let refItem = refArray[i]
            if (refItem.state.validateSuccess === true) {
                const validateRef = await refItem.validateRules()
                if (validateRef === false) {
                    validateResult = false
                    validateMessageArr = [...validateMessageArr, ...refItem.state.validateMessageArr]
                }
            } else {
                validateResult = false
                validateMessageArr = [...validateMessageArr, ...refItem.state.validateMessageArr]
            }
        }
    }
    if (validateResult === false) {
        validateMessageArr.forEach(item => {
            message.warning(item)
        })
    }
    return validateResult
}

const formValidate = {
    getValidater,
    validateForm
}
export default formValidate